﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataService;
using Newtonsoft.Json;

namespace CheatService
{
    /// <summary>
    /// Summary description for UserContorl
    /// </summary>
    public static class UserContorl
    {
        private static readonly float AliveElependTime;
        static UserContorl()
        {
            AliveElependTime = 60000;
        }

        /// <summary>
        /// remove un alive talker
        /// </summary>
        public static void RemoveOfflineUser()
        {
            IList<Talker> regestUsers = CacheFactory.GetCacheService<Talker>(CacheFactory.UserListKey).GetValues();
            for (int i = regestUsers.Count; i <= 0; i--)
            {
                if (regestUsers[i].LastActiveTime.AddSeconds(AliveElependTime) < DateTime.Now)
                {
                    regestUsers.RemoveAt(i);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static IList<Talker>  GetOnlineUser()
        {
            return CacheFactory.GetCacheService<Talker>(CacheFactory.UserListKey).GetValues();
        }

        public static string OnListenComing(string talkerKey)
        {
            IList<Talker> talkers = CacheFactory.GetCacheService<Talker>(CacheFactory.UserListKey).GetValues();
            Talker currentTalker = talkers.First(t => t.Key == talkerKey);
            currentTalker.UpdateActiveTime();
            //userList
            EventData userEvent = new EventData(EventType.UserList);
            userEvent.Body = JsonConvert.SerializeObject(talkers);
            //Message
            IEnumerable<Message> myMessages = MessageControl.GetMessages(talkerKey);
            EventData messageEvent = new EventData(EventType.Message);
            messageEvent.Body = JsonConvert.SerializeObject(myMessages);
            EventData[] events = new EventData[2] { userEvent, messageEvent };
            return JsonConvert.SerializeObject(events);
        }

        public static string OnTalkerFirstComing(string talkerKey)
        {
            if (string.IsNullOrEmpty(talkerKey))
            {
                Guid guid = Guid.NewGuid();
                talkerKey = guid.ToString();
            }
            Talker talker = new Talker();
            talker.Key = talkerKey;
            talker.UpdateActiveTime();
            ICacheService<Talker> cache = CacheFactory.GetCacheService<Talker>(CacheFactory.UserListKey);
            cache.Add(talker);
            return talkerKey;
        }
    }
}